//===================================================
//Author      : GCL
//CreateTime  ：2/1/2019 12:51:52 PM
//Description ：
//===================================================
using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System.IO;


public class MetaDataDBManager : MonoBehaviour {

	public string DBName = "tsplaymetadata.db";
	
	void Awake()
	{

		GameObject dataManager = GameObject.Find("MetaDataDBManager");
		_instance = dataManager.GetComponent<MetaDataDBManager>();
		DontDestroyOnLoad(dataManager);

	}

	protected SQLiteHelper dbConnector = null;

	private static MetaDataDBManager _instance = null;
	public static MetaDataDBManager Instance
	{      
		get
		{
			if( _instance != null )
			{
				if(_instance.dbConnector != null )
				{
					return _instance;
				}
			}

			string path = "";
			Debug.Log("Prepare db");

#if UNITY_EDITOR
			path = Application.dataPath + "/StreamingAssets";
			Debug.Log("UNITY_EDITOR Start");
#elif UNITY_ANDROID 
			string filepath = Application.persistentDataPath + "/" + _instance.DBName;
			Debug.Log("Android Platform Start");
			//if(!File.Exists(filepath))
			{
			 
			    // if it doesn't ->
			 
			    // open StreamingAssets directory and load the db ->
			 
				WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + _instance.DBName);  // this is the path to your StreamingAssets in android
			 
			    while(!loadDB.isDone) {}  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
			 
			    // then save to Application.persistentDataPath
			 
			    File.WriteAllBytes(filepath, loadDB.bytes);
			 
			}		

			path = Application.persistentDataPath;
			Debug.Log("Android Platform");

	#elif UNITY_IOS
			Debug.Log("iOS Platform Start");
			path = Application.dataPath + "/Raw";
			string filepath = Application.persistentDataPath + "/" + _instance.DBName;

			FileInfo fi = new FileInfo(filepath);
			if(!fi.Exists){
				
				// if it doesn't ->
				
				// open StreamingAssets directory and load the db ->
				Debug.Log("start copy-----------------------------");
				Debug.Log("copy "+_instance.DBName+" From "+path+" to "+Application.persistentDataPath);
				DataTable.DataUtility.CopyFile(path+"/"+_instance.DBName,filepath,1024*1024);
				
//
//				WWW loadDB = new WWW(path+"/"+_instance.DBName);  // this is the path to your StreamingAssets in android
//
//				while(!loadDB.isDone) {}  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check

				// then save to Application.persistentDataPath

				//File.WriteAllBytes(filepath, loadDB.bytes);
				XLogger.Log("coping file is ok ----------------");
			}
			path = Application.persistentDataPath;
			Debug.Log("iOS Platform");
#else
			Debug.Log("Else Platform");
			path = Application.dataPath + "/StreamingAssets";
#endif
			path += "/"+_instance.DBName;
			_instance.dbConnector = new SQLiteHelper("URI=file:" + path);
			Debug.Log("DB Connector was ready !");
			return _instance;
		}
	}
	//ReadTable ("table1", new string[]{"ID","Name"}, new string[]{"Age"}, new string[]{">="}, new string[]{"'25'"});
	public SqliteDataReader ReadTable(string tableName,string[] items,string[] colNames,string[] operations, string[] colValues)
	{
		return dbConnector.ReadTable (tableName, items, colNames, operations, colValues);
	}
	public SqliteDataReader ExecuteQuery(string queryString)
	{
		return dbConnector.ExecuteQuery(queryString);
	}
	void OnDisable()
	{
        Debug.Log("db was colsed");
        Disconnect();

    }
    protected void Disconnect()
    {
        if( dbConnector == null )
            return;
        dbConnector.CloseConnection();
        dbConnector = null;
        Debug.Log( "db was colsed" );
    }
	void OnDestroy()
	{
        Disconnect();

    }
}
